package com.wang.bootbuilder.controller.captcha;

import com.google.code.kaptcha.Producer;
import com.wang.bootbuilder.controller.base.BaseController;
import com.wang.bootbuilder.tools.Const;
import com.wang.bootbuilder.tools.JsonResult;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/manage")
@Api(value = "/manage/captcha", description = "处理验证码相关请求的controller")
public class CaptchaController extends BaseController {

    @Autowired
    Producer peoducer;

    @GetMapping("/captcha")
    public JsonResult captcha() throws IOException {

        String key = UUID.randomUUID().toString();
        String code = peoducer.createText();

        BufferedImage image = peoducer.createImage(code);
        ByteArrayOutputStream ops = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", ops);

        BASE64Encoder encoder = new BASE64Encoder();
        String prefix = "data:image/jpeg;base64,";
        String base64Image = prefix + encoder.encode(ops.toByteArray());

        // 把验证码存入redis
        redisUtils.hset(Const.CAPTCHA_KEY, key, code, 120);

        return JsonResult.ok().data("captcha", base64Image).data("key", key);

    }
}
